package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    /**
     * 根据用户名获取用户信息(用户名，密码，权限)
     * @param username
     * @return
     */
    @Override
    public SysUser findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {

        //1. 开始分页(把页面和每页条数封装成Page，并存储到ThreadLocal中)
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //2. 条件查询(请求会被拦截器拦截，根据page参数和映射文件中的sql语句拼接 分页查询的sql语句)
        Page<SysUser> page = userDao.findByCondition(queryPageBean.getQueryString());List<SysUser> sysUserList = page.getResult();

        //3. 返回结构
        return new PageResult(page.getTotal(), page);
    }

    @Override
    @Transactional
    public void add(SysUser sysUser, Integer[] roleIds)  {
        userDao.add(sysUser);
        set(sysUser,roleIds);
    }

    public void set(SysUser sysUser, Integer[] roleIds){
        if(sysUser.getId() != null && roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                //维护关系
                userDao.set(sysUser.getId(), roleId);
            }
        }
    }

    @Override
    public SysUser findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsById(Integer id) {
        return userDao.findRoleIdsById(id);
    }

    @Override
    @Transactional
    public void edit(SysUser sysUser, Integer[] roleIds) {
        userDao.edit(sysUser);
        userDao.delRelation(sysUser.getId());
        set(sysUser,roleIds);
    }


    @Override
    public void delById(Integer id) {
        long count = userDao.findCountById(id);
        if(count > 0){
            throw new RuntimeException("该用户与角色有关联，不能删除！！！");
        }
        //2. 删除检查组和检查项的关系
        userDao.delRelation(id);
        //3. 删除检查组
        userDao.delById(id);
    }



}
